from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth import authenticate, login,logout
from .forms import UserLoginForm

# Create your views here.

def user_login(request):
    if request.method == "POST":
        user_login_form = UserLoginForm(data=request.POST)
        if user_login_form.is_valid():
            data = user_login_form.cleaned_data
            user = authenticate(username=data['username'], password=data['password'])
            if user:
                login(request, user)
                return redirect('bookcms:list')
            else:
                return HttpResponse("密码错误")
        else:
            return HttpResponse("请输入合法的账号密码")

    elif request.method == "GET":
        user_login_form = UserLoginForm()
        return render(request, "login.html", {
            "user_login_form": user_login_form,
        })
    else:
        return HttpResponse("请使用get or post 进行请求")
    
    
def user_logout(request):
    logout(request)
    return redirect("bookcms:list")